#include <iostream>
#include <semaphore>
#include <thread>
#include <vector>

std::counting_semaphore<3> sem(3);  // 最多允许 3 个线程同时执行

void worker(int id) {
    std::cout << "Worker " << id << " waiting for semaphore...\n";
    sem.acquire();  // 获取信号量
    std::cout << "Worker " << id << " acquired semaphore, working...\n";

    // 模拟一些工作
    std::this_thread::sleep_for(std::chrono::seconds(1));

    std::cout << "Worker " << id << " releasing semaphore...\n";
    sem.release();  // 释放信号量
}

int main() {
    std::vector<std::thread> threads;

    // 创建多个线程来测试信号量
    for (int i = 0; i < 5; ++i) {
        threads.push_back(std::thread(worker, i));
    }

    // 等待所有线程完成
    for (auto& t : threads) {
        t.join();
    }

    return 0;
}